<template>
    <div id="map-wrapper">
        <button @click="fitMapView(zoom)" class="btn return-btn">还原</button>
        <div id="container" ref="mapContainer" style="width: 100%; height: 100%;"></div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, defineProps } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';

const props = defineProps({
    location: {
        type: Array,
        default: () => [87.618000,43.824599],
    },
    marksPosition: {
        type: Array,
        default: () => [[87.618000,43.824599]],
    }
});

const mapContainer = ref(null);
let map = null;
let markers = [];
let zoom = 16;

onMounted(() => {
    window._AMapSecurityConfig = {
        securityJsCode: 'a37b057e319b17c0f41efd30ac8e7f01', // 高德地图API密钥 57376839cd5b5539ea809b798d9697ad 
    };

    AMapLoader.load({
        key: 'aceb229cbcf9827134f48bc022aa99da', // 高德地图API密钥 a5b01eff66b908a39486a2664fbc7ac0
        version: '2.0',
        plugins: [], // 加载插件  
    }).then((AMap) => {
        map = new AMap.Map(mapContainer.value, {
            resizeEnable: true,
            center: props.location, // 地图中心点  
            zoom: zoom, // 地图显示的缩放级别  
        });

        map.clearMap(); // 清除地图覆盖物

        // 初始化标记  
        initMarkers();

        // 监听location属性的变化，并更新地图中心点  
        watch(() => props.location, (newLocation) => {
            console.log("location: " + newLocation)
            if (map && newLocation) {
                map.setCenter(newLocation);
            }
        });

        // 监听marksPosition属性的变化，并更新标记位置  
        watch(() => props.marksPosition, (newPositions) => {
            console.log("newPositions: " + newPositions);

            // 清除旧标记  
            markers.forEach(marker => marker.setMap(null)); // 清除所有标记  
            markers = []; // 重置标记数组  
            initMarkers(newPositions); // 初始化新标记  
        });

        function initMarkers(positions = props.marksPosition) {
            markers = [];
            positions.forEach((position) => {
                const marker = new AMap.Marker({
                    map: map,
                    icon: require('../../assets/images/mark_r.png'),
                    position: position,
                    offset: new AMap.Pixel(-3, -13)
                });
                markers.push(marker); // 存储标记以便后续清除  
            });
        }
    });
});

function fitMapView(zoom) {
    map.setCenter(props.location);
    map.setZoom(zoom);
}

onUnmounted(() => {
    // 组件卸载时清理资源
    if (map) {
        markers.forEach(marker => marker.setMap(null)); // 清除所有标记  
        markers = []; // 重置标记数组  
        map.destroy();
        map = null;
    }
});
</script>
<style lang="scss">
#map-wrapper {
    width: 100%;
    height: 100%;

    .return-btn {
        position: absolute;
        float: right;
        margin: 3px;
        background-color: #fff;
        z-index: 100;
    }

    .return-btn:hover {
        background-color: #fafafa;
    }
}
</style>
